package com.liwbn.rbac.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liwbn.rbac.exception.JsonReException;
import com.liwbn.rbac.service.PermissionService;
import com.liwbn.rbac.service.RolePermissionService;
import com.liwbn.rbac.service.RoleService;
import com.liwbn.rbac.support.ExceptionCode;
import com.liwbn.rbac.support.JsonReInfo;
import com.liwbn.rbac.vo.RolePermissionVO;
import com.liwbn.rbac.vo.SideBar;

/**
 * 角色权限管理表
 * 
 * @author liwb
 */
@Controller
public class RoleModuleController {

    @Autowired
    private PermissionService service;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * 返回页面
     * 
     * @return
     */
    @RequestMapping("/system/roleMudule")
    public String showRoleModulePage() {
        return "system/roleModule";
    }

    /**
     * 获取菜单权限树
     * 
     * @return
     */
    @RequestMapping("/system/getMenuModule")
    @ResponseBody
    public String getMenuModule() {
        List<SideBar> sb = null;
        try {
            sb = service.selectPermission();
        } catch (Exception e) {
            throw new JsonReException(101, ExceptionCode.CODE_101_EXCEPTION, e);
        }
        return new JsonReInfo(100, sb).toString();
    }

    /**
     * 获取所有的角色权限信息
     * 
     * @return
     */
    @RequestMapping("/system/getRoles")
    @ResponseBody
    public String getRoles() {
        try {
            List<RolePermissionVO> roles = roleService
                    .selectAllRolesAndPermission();
            return new JsonReInfo(100, roles).toString();
        } catch (Exception e) {
            throw new JsonReException(101, ExceptionCode.CODE_101_EXCEPTION, e);
        }
    }

    /**
     * 保存权限信息修改
     * 
     * @return
     */
    @RequestMapping("/system/changePermission")
    @ResponseBody
    public String changePermission(String role, String permission) {
        try {
            if (!StringUtils.isNotBlank(permission)) {
                permission = "";
            }
            Map<String, String> permiss = new HashMap<String, String>();
            permiss.put(role, permission);
            rolePermissionService.updatePermissionByRole(permiss);
            return new JsonReInfo(100, ExceptionCode.CODE_100_EXCEPTION)
                    .toString();
        } catch (Exception e) {
            throw new JsonReException(101, ExceptionCode.CODE_101_EXCEPTION, e);
        }
    }
}
